﻿using System;
 
using System.Web.Mvc;
using CarTrackr.Business;
using CarTrackr.Business.Services;
 

namespace CarTrackr.Controllers
{
    
    [Authorize]
    public class RefuellingController : Controller
    {
     
        private IAppService service;
 
        public RefuellingController(): this(new AppService())
        {
           
        }

        public RefuellingController(IAppService appService)
        {
           service = appService;
        }


        public ActionResult Index()
        {
            return RedirectToAction("List", "Car");
        }

        public ActionResult List(string licensePlate)
        {
            Car car =  service.GetCarByLicensePlate(licensePlate);

            car.Refuellings = service.ListRefuellings(car.Id);
     
            return View("List", car);
        }

       
        public ActionResult New(string licensePlate)
        {
            Car car = service.GetCarByLicensePlate((licensePlate));
            car.Refuellings = service.ListRefuellings(car.Id);

            ViewData["Date"] = DateTime.Now.ToString("dd/MM/yyyy");

            return View("New", car);
        }

        [HttpPost]
        public ActionResult New(string licensePlate, FormCollection form)
        {
                Car car = service.GetCarByLicensePlate(licensePlate);

                var refuelling = new Refuelling();
              
                refuelling.Date = DateTime.Parse(form["Date"]);
                refuelling.ServiceStation = form["ServiceStation"];
                refuelling.Kilometers = Decimal.Parse(form["Kilometers"]);
                refuelling.Liters = Decimal.Parse(form["Liters"]);

   
                if (refuelling.IsValid)
                {
                    service.AddRefuelling(refuelling, car.Id);
                    return RedirectToAction("List", new { licensePlate });
                }


                 ModelState.UpdateWithViolation(refuelling);
          

                return View("New", car);
           
       }

      

        public ActionResult Remove(Guid id,string licensePlate)
        {
           
            service.RemoveRefuelling(id);

            return RedirectToAction("List", new { licensePlate });
        }
            

    }
}
 